package com.chijun.mform.full.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.chijun.mform.FormUtils;
import com.chijun.mform.R;
import com.chijun.mform.create.mode.FormField;
import com.chijun.mform.create.mode.FormFieldOption;
import com.chijun.mform.create.mode.FormOptionReField;
import com.chijun.mform.field.BaseField;
import com.chijun.mform.field.FieldFullViewUtil;
import com.chijun.mform.full.IHandleWriterData;
import com.chijun.mform.full.mode.ModeFormFile;
import com.chijun.mform.full.mode.ModeFormOrdinaryFieldData;
import com.chijun.mform.full.mode.ModeLoadServerFormConfigData;
import com.chijun.mform.process.OptionChangeListener;
import com.example.ccj.b.c.dialog.ErrorDialog;
import com.example.ccj.b.c.dialog.LoadingDialog;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.StringUtils;
import com.example.ccj.u.server.MyObserver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 加载表单字段数据
 *
 * @author 驰珺
 * whechat   : chijun9
 * create at : 2024/12/2 9:33
 */
public class ViewLoadFormField extends LinearLayout implements OptionChangeListener {

    //关联表单靠这个回调实现
    private IHandleWriterData iHandleWriterData;                //
    private ModeLoadServerFormConfigData writeFormData;                        //表单配置
    Map<FormField,BaseField> formFieldFieldViewMap;             //加载的字段数据  字段配置，字段对应的view
    List<ModeFormFile> saveSqlImageModeList;                    //需要保存的文件数据
    List<ModeFormOrdinaryFieldData> saveSqlOrdinaryFieldDataList;   //需要保存的普通字段数据


    public ViewLoadFormField(Context context, ModeLoadServerFormConfigData writeFormData) {
        super(context);
        this.writeFormData = writeFormData;
        innn();
    }

    public ViewLoadFormField(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setFormData(ModeLoadServerFormConfigData writeFormData){
        this.writeFormData = writeFormData;
        innn();
    }

    Map<Long, View> allFieldView;

    private void innn(){
        allFieldView = new HashMap<>();
        LinearLayout.inflate(getContext(), R.layout.view_load_form_field,this);
        LinearLayout layout = findViewById(R.id.view_load_form_field_layout);
        formFieldFieldViewMap = new HashMap<>();

        //获取本地保存的值
        Observable.create(new ObservableOnSubscribe<Pair<View,Boolean>>() {
                    @Override
                    public void subscribe(ObservableEmitter<Pair<View,Boolean>> e) throws Exception {
                        //所有关联字段
                        List<Long> allReFieldId = new ArrayList<>();
                        for (List<Long> value : writeFormData.formOptionReFieldMap.values()) allReFieldId.addAll(value);
                        //加载字段
                        for (FormField formField : writeFormData.formFieldList) {
                            BaseField fieldModel = FieldFullViewUtil.getFieldModelByType(formField.getType());
                            View fieldFullView = fieldModel.getWritelView(getContext(), formField, writeFormData, iHandleWriterData,ViewLoadFormField.this);
                            allFieldView.put(formField.getId(),fieldFullView);
                            formFieldFieldViewMap.put(formField,fieldModel);

                            //判断该字段是否显示 和选项关联了就不显示，未关联就显示
                            if (allReFieldId.contains(formField.getId())) e.onNext(new Pair<>(fieldFullView,false));
                            else e.onNext(new Pair<>(fieldFullView,true));
                        }
                        e.onComplete();
                    }
                }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<Pair<View,Boolean>>() {
                    @Override
                    public void onNext(Pair<View,Boolean> fieldView) {
                        if (fieldView.second) fieldView.first.setVisibility(VISIBLE);
                        else fieldView.first.setVisibility(GONE);
                        layout.addView(fieldView.first,layoutParams);
                    }
                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                    @Override
                    public void onError(Throwable e) {
                        ErrorDialog errorDialog = new ErrorDialog(getContext(),e.getMessage());
                        errorDialog.show();
                        super.onError(e);
                    }
                });
    }

    LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    public boolean check(){
        saveSqlImageModeList = new ArrayList<>();
        saveSqlOrdinaryFieldDataList = new ArrayList<>();

        boolean isOk = true;

        //单项选择和多项选择保存选项的id
        //日期保存时间戳，日期区间保存 开始日期时间戳-结束日期时间戳
        //图片保存在单独sql表
        StringBuilder errorStr = new StringBuilder();
        for (FormField formField : formFieldFieldViewMap.keySet()) {
            BaseField fieldView = formFieldFieldViewMap.get(formField);

            if (fieldView != null) {
                //图片、附件字段处理
                if (formField.getType() == FormField.TU_PIAN || formField.getType() == FormField.FU_JIAN || formField.getType() == FormField.SHOU_XIE) {
                    List<ModeFormFile> imageModes = fieldView.getFormFileModeList();

                    if (formField.isMast() && imageModes.isEmpty()) {
                        errorStr.append(formField.getName()).append("不可为空！").append("\n");
                        LogUtils.e(formField.getName()+"可不为空！");
                        isOk = false;
                        continue;
                    }
                    saveSqlImageModeList.addAll(imageModes);
                //获取普通字段的值
                } else {
                    if (formField.isMast() && StringUtils.isEmpty(fieldView.getSaveValue())) {
                        errorStr.append(formField.getName()).append("不可为空！").append("\n");
                        LogUtils.e(formField.getName()+"可不为空！");
                        isOk = false;
                    }
                    if (fieldView.getSaveValue() == null) continue;
                    ModeFormOrdinaryFieldData formOrdinaryFieldData = new ModeFormOrdinaryFieldData();
                    formOrdinaryFieldData.formId = formField.getFormId();
                    formOrdinaryFieldData.formFullId = writeFormData.id;
                    formOrdinaryFieldData.fieldId = formField.getId();
                    formOrdinaryFieldData.content = fieldView.getSaveValue().toString();
                    saveSqlOrdinaryFieldDataList.add(formOrdinaryFieldData);
                }
            }
        }

        if (!isOk) {
            ErrorDialog dialog = new ErrorDialog(getContext(),errorStr.toString());
            dialog.show();
        }

        return isOk;
    }

    /**
     * 选项发生改变时的事件
     * 1、先获取该字段所有选项所关联的字段
     * 2、再获取当前选择的选项所关联的字段
     * 3、两者对比
     * @param fieldId 字段id
     * @param formFieldOptionList 当前的选项
     */
    @Override
    public void onChanged(long fieldId, FormFieldOption... formFieldOptionList) {

        List<FormFieldOption> formFieldOptions = writeFormData.getFormFieldOptionMap().get(fieldId);
        if (formFieldOptions != null) {
            List<Long> formFieldAllOptionsIdList = new ArrayList<>();
            Map<Long,Long[]> formOptionAllReFieldMap = new HashMap<>();
            Long[] selectOptionIdArray = new Long[formFieldOptionList.length];

            for (FormFieldOption formFieldOption : formFieldOptions) {
                formFieldAllOptionsIdList.add(formFieldOption.id);
            }
            for (Long l : writeFormData.formOptionReFieldMap.keySet()) {
                List<Long> formOptionReFields = writeFormData.formOptionReFieldMap.get(l);
                if (formOptionReFields != null) {
                    Long[] linshi =  new Long[formOptionReFields.size()];
                    for (int i = 0; i < formOptionReFields.size(); i++) {
                        linshi[i] = formOptionReFields.get(i);
                    }
                    formOptionAllReFieldMap.put(l,linshi);
                }
            }

            for (int i = 0; i < formFieldOptionList.length; i++) {
                selectOptionIdArray[i] = formFieldOptionList[i].id;
            }

            FormUtils.FieldOptionChanged(allFieldView,formFieldAllOptionsIdList,formOptionAllReFieldMap,selectOptionIdArray);
        }
    }

    private void setText(TextView text,CharSequence t){
        text.post(() -> text.setText(t));
    }

    public IHandleWriterData getiHandleWriterData() {
        return iHandleWriterData;
    }

    public void setiHandleWriterData(IHandleWriterData iHandleWriterData) {
        this.iHandleWriterData = iHandleWriterData;
    }


    public List<ModeFormFile> getSaveSqlImageModeList() {
        return saveSqlImageModeList;
    }

    public void setSaveSqlImageModeList(List<ModeFormFile> saveSqlImageModeList) {
        this.saveSqlImageModeList = saveSqlImageModeList;
    }

    public List<ModeFormOrdinaryFieldData> getSaveSqlOrdinaryFieldDataList() {
        return saveSqlOrdinaryFieldDataList;
    }

    public void setSaveSqlOrdinaryFieldDataList(List<ModeFormOrdinaryFieldData> saveSqlOrdinaryFieldDataList) {
        this.saveSqlOrdinaryFieldDataList = saveSqlOrdinaryFieldDataList;
    }


}
